package ar.com.nexttome.tasks;

import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import ar.com.nexttome.MainActivity;
import ar.com.nexttome.MensajesActivity;
import ar.com.nexttome.PerfilActivity;
import ar.com.nexttome.PersonaActivity;
import ar.com.nexttome.PersonaManager;
import ar.com.nexttome.R;
import ar.com.nexttome.context.ApplicationContext;
import ar.com.nexttome.entities.Persona;
import ar.com.nexttome.util.Constantes;
import ar.com.nexttome.util.PersonaArrayAdapter;
import ar.com.nexttome.util.Tools;

public class BuscarPersonasTask extends AsyncTask<String, Void, List<Persona>> {
	private MainActivity activity;

	public BuscarPersonasTask(MainActivity activity) {
		super();
		this.activity = activity;
	}

	protected void onPreExecute() {
		Toast.makeText(activity, Constantes.STR_AGUARDE, Toast.LENGTH_SHORT).show();
	}

	protected List<Persona> doInBackground(String... params) {
		ApplicationContext appctx = (ApplicationContext) activity.getApplicationContext();
		Persona yo = appctx.getCurrentUser();
		List<Persona> listPersonas = PersonaManager.getPersonas(yo.getId());
		appctx.setListPersonas(listPersonas);

		return listPersonas;
	}

	protected void onPostExecute(List<Persona> listPersonas) {

		if (listPersonas == null) {
			Tools.alertReintentar(activity, Constantes.STR_CERCANOS_ERROR);
		} else if (listPersonas.size() == 0) {
			Tools.alertReintentar(activity, Constantes.STR_NO_CERCANOS);
		} else {
			activity.setContentView(R.layout.list);

			Tools.createActionMenu(activity, Constantes.STR_CERCANOS, MensajesActivity.class, R.drawable.ic_title_export_default);
			Tools.createActionMenu(activity, Constantes.STR_CERCANOS, PerfilActivity.class, R.drawable.ic_title_home_default);

			ListAdapter adapter = new PersonaArrayAdapter(activity, listPersonas);
			final ListView lv = (ListView) activity.findViewById(R.id.listView1);
			lv.setAdapter(adapter);

			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

					Persona personaSeleccionada = (Persona) lv.getItemAtPosition(position);
					((ApplicationContext) activity.getApplicationContext()).setPersonaSeleccionada(personaSeleccionada);
					
					Intent intent = new Intent(activity, PersonaActivity.class);
			        activity.startActivity(intent);
				}
			});
		}
	}
}